import Taro, { Component } from '@tarojs/taro'
import { View } from '@tarojs/components'
import _isEmpty from 'lodash/isEmpty'
import AddressSelectorResultItem from '../../components/AddressSelectorResultItem'
import AddressSearch from '../../components/AddressSearch'
import { divisionCityStr } from '@/utils'
import './index.scss'

class AddressSelector extends Component {
  config = {
    navigationBarTitleText: '城市地区',
  }

  constructor(props) {
    super(props)
  }

  state = {
    inputValue: '',
    mapCtx: null,
    cityList: []
  }

  componentDidShow () {
    this.initMap()
    console.log('地址===', Taro.getStorageSync('map_select_city'))
  }

  componentWillUnmount () {
    this.setState({
      mapCtx: null
    })
  }

  initMap = () => {
    var map = new AMap.Map('addressselector-container', {
      zoom: 14,
      resizeEnable: true,
    })
    this.setState({
      mapCtx: map
    })
    setTimeout(() => {
      this.initMapHelper()
    })
  }

  initMapHelper = () => {
    const { mapCtx } = this.state
    var _this = this
    mapCtx.plugin('AMap.Geolocation', function() {
      var geolocation = new AMap.Geolocation({
        enableHighAccuracy: true, //是否使用高精度定位，默认:true
        timeout: 5000, //超过10秒后停止定位，默认：无穷大
        maximumAge: 0, //定位结果缓存0毫秒，默认：0
        convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
        showButton: true, //显示定位按钮，默认：true
        buttonPosition: 'LB', //定位按钮停靠位置，默认：'LB'，左下角
        buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
        showMarker: true, //定位成功后在定位到的位置显示点标记，默认：true
        showCircle: true, //定位成功后用圆圈表示定位精度范围，默认：true
        panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
        zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
      })
      mapCtx.addControl(geolocation)
      // geolocation.getCurrentPosition(function(status, result) {
      //   if (status == 'complete') {
      //     _this.onComplete(result)
      //   } else {
      //     _this.onError(result)
      //   }
      // })
    })
    //输入提示
    var autoOptions = {
      input: 'map-input',
    }
    var auto
    mapCtx.plugin('AMap.Autocomplete', function() {
      auto = new AMap.Autocomplete(autoOptions)
    })
    
    mapCtx.plugin('AMap.PlaceSearch', function() {
      var placeSearch = new AMap.PlaceSearch(autoOptions)
      AMap.event.addListener(auto, 'select', select) //注册监听，当选中某条记录时会触发
      function select(e) {
        const cd = {
          city: e.poi.district,
          address: e.poi.address,
          code: e.poi.adcode,
        }
        _this.setState({
          inputValue: e.poi.district,
          cityList: [ cd ]
        })
        placeSearch.setCity(e.poi.adcode)
        placeSearch.search(e.poi.name) //关键字查询查询
        var point = [e.poi.location.lng, e.poi.location.lat]
      
        var marker = new AMap.Marker({position: point})
        mapCtx.add(marker)
        mapCtx.panTo(point)
      }
     
    })//构造地点查询类
    
  }

  onComplete = data => {
    // this.completeFunc(data)
    console.log('定位成功==', data)
  }

  onError = data => {
    console.log(data)
    var str = '定位失败,'
    str += '错误信息：'
    switch (data.info) {
      case 'PERMISSION_DENIED':
        str += '浏览器阻止了定位操作'
        break
      case 'POSITION_UNAVAILBLE':
        str += '无法获得当前位置'
        break
      case 'TIMEOUT':
        str += '定位超时'
        break
      default:
        str += '未知错误'
        break
    }
    console.log('str', str)
  }

  onChange = (e) => {
    console.log(e)
  }

  render() {
    const { inputValue, cityList } = this.state
    return (
      <View className="addressselector-page">
        <View id="addressselector-container"></View>
        <View className="search-input">
          <AddressSearch
            paddingBg="transparent"
            inputBg="#FFF"
            hasShadow
            id="map-input"
            onChange={(e) => this.onChange(e)}
            value={inputValue}
          ></AddressSearch>
        </View>
        <View className="select-result-box">
          {!_isEmpty(cityList) && cityList.map((cl, index) => {
            return (
              <AddressSelectorResultItem
                key={'city_12_'+index}
                curIndex={index}
                city={cl.city}
                detail={cl.address || ''}
                onClick={() => {
                  const cd = Taro.getStorageSync('map_select_city')
                  const parr = divisionCityStr(cl.city)
                  const md = {
                    ...cd, 
                    address: cl.address,
                    ...parr,
                  }
                  setTimeout(()=> {
                    console.log('md==', md)

                    Taro.setStorageSync('map_select_city', md)
                    Taro.navigateBack()
                  }, 200)
                  
                }}
              ></AddressSelectorResultItem>
            )
          })}
        </View>
      </View>
    )
  }
}

export default AddressSelector
